package BugzillaJsonRpc::Client;
use 5.018;
use warnings;
use Carp qw(confess);

use Mojo::UserAgent;
my $ua = Mojo::UserAgent->new;

use BugzillaJsonRpc::Config;
my $cfg = BugzillaJsonRpc::Config->new;
my $host = $cfg->{host};
my $url = "$host/jsonrpc.cgi";

use Data::Dumper;
use Mojo::JSON qw(true false);
use DTask::Utils qw(wrapUATX);

sub call
{
	my ($method, $params, $cb) = @_;
	my $token = $BugzillaJsonRpc::User::token;
	warn "token is lose" unless $token;
	$params->{Bugzilla_token} = $token;

	my $callobj = {
		version => '2.0',
		method => $method,
		params => $params,
	};


	warn 'url is '. $url;
	warn 'call: dump $callobj';
	warn Dumper $callobj;

	$ua->post($url => { 'Content-Type' => 'application/json-rpc'} , json => $callobj, sub {
		my $ret = wrapUATX(@_);
		unless ($ret->{error})
		{
			if (my $err = $ret->{result}{error} )
			{
				
				my $err_str = $err->{name} . ' ' . $err->{code} . ' : '. $err->{message};
				$ret = {error => true, error_message => $err_str };

			}
			else
			{
				my $result = $ret->{result}{result};
				$ret = {error => false, result => $result};
			}
		}

		$cb->($ret);
	});
}


1;




